import { Form, Input, message, Modal, Select } from 'antd';
import React, { useState } from 'react';
import { GlobalFormLayout } from '@/layouts/Form';
import request from '@/utils/request';
import CatalogTreeSelect from '@/components/CatalogTreeSelect';

function ValidationEditModal({ visible, onClose, onOk, data = {}, form }) {
  const { getFieldDecorator, validateFields } = form;
  const { validationId, validationName, validationCode, messageFormat, parentCatalogId } = data;
  const isEdit = !!validationId;
  const [loading, setLoading] = useState(false);

  const handleSubmit = () => {
    validateFields((err, data) => {
      if (!err) {
        const url = `/validation/${isEdit ? 'update' : 'create'}Validation`;
        setLoading(true);
        request
          .post(url, { data })
          .then(() => {
            message.success(isEdit ? '修改成功' : '创建成功');
            onClose();
            onOk();
          })
          .finally(() => setLoading(false));
      }
    });
  };

  return (
    <Modal
      title={isEdit ? '修改校验器' : '新增校验器'}
      visible={visible}
      onCancel={onClose}
      destroyOnClose
      confirmLoading={loading}
      onOk={() => handleSubmit()}
    >
      <Form {...GlobalFormLayout}>
        {validationId && (
          <Form.Item>
            {getFieldDecorator('validationId', {
              initialValue: validationId,
            })(<Input hidden />)}
          </Form.Item>
        )}
        <Form.Item label="上级目录">
          {getFieldDecorator('parentCatalogId', {
            initialValue: parentCatalogId,
          })(<CatalogTreeSelect code="validation" />)}
        </Form.Item>
        <Form.Item label="校验器名称">
          {getFieldDecorator('validationName', {
            initialValue: validationName,
            rules: [
              {
                required: true,
                message: '校验器名称不能为空',
              },
            ],
          })(<Input placeholder="请输入" />)}
        </Form.Item>
        <Form.Item label="校验器编码">
          {getFieldDecorator('validationCode', {
            initialValue: validationCode,
            rules: [
              {
                required: true,
                message: '校验器编码不能为空',
              },
            ],
          })(<Input placeholder="请输入" />)}
        </Form.Item>
        <Form.Item label="报文格式">
          {getFieldDecorator('messageFormat', {
            initialValue: messageFormat || 'JSON',
            rules: [
              {
                required: true,
                message: '报文格式不能为空',
              },
            ],
          })(
            <Select>
              <Select.Option value="JSON">JSON</Select.Option>
              <Select.Option value="XML">XML</Select.Option>
            </Select>
          )}
        </Form.Item>
      </Form>
    </Modal>
  );
}

export default Form.create()(ValidationEditModal);
